package seg.tef4.whms.util.auth;

import android.content.Context;
import android.content.Intent;

import java.time.Duration;
import java.time.LocalDateTime;

import seg.tef4.whms.activity.LoginActivity;
import seg.tef4.whms.activity.activityinit.BaseActivity;
import seg.tef4.whms.activity.activityinit.SubBaseActivity;
import seg.tef4.whms.domain.entity.SysUser;
import seg.tef4.whms.util.dialog.AlertDialogCreator;

public class OnlineUser {
    private static String token;
    private static LocalDateTime lastTime;

    private static SysUser sysUser;

    private static long token_time = 5;

    /**
     * @description 初始化Token,及其时间
     * @param token
     */
    public static void setToken(String token){
        OnlineUser.token = "Bearer " + token;
        lastTime = LocalDateTime.now();
    }

    public static boolean checkTokenTimeExceed(){
        LocalDateTime now = LocalDateTime.now();
        Duration duration = Duration.between(lastTime, now);

        long minutes = duration.toMinutes();
        if(minutes >= token_time){
            lastTime = null;
            sysUser = null;
            return true;
        }

        return false;
    }

    /**
     * @description 获取Token：每次获取Token时更新Token时间
     * @return
     */
    public static String getToken(Context context){
        boolean tokenExceed = checkTokenTimeExceed();
        if(tokenExceed){
            AlertDialogCreator.getConfirmDialog(context,
                    "登陆超时", "由于长时间未操作，因而需要重新登陆", "确认", (dialogInterface, i) -> {
                        Intent intent = new Intent(context, LoginActivity.class);
                        //清空所有活动栈，让新启动的活动成为唯一根活动
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        context.startActivity(intent);
                    }).show();
        }
        lastTime = LocalDateTime.now();
        return token;
    }

    public static void setSysUser(SysUser sysUser){
        OnlineUser.sysUser = sysUser;
    }

    public static SysUser getSysUser(){
        return sysUser;
    }
}
